import React, { useState, useEffect } from 'react';
import { Card, CardContent, CardHeader, CardTitle } from './ui/card';
import { Button } from './ui/button';
import { Badge } from './ui/badge';
import { Progress } from './ui/progress';
import { GitBranch, Clock, Trophy, Star, CheckCircle, XCircle, RotateCcw } from 'lucide-react';
import { motion, AnimatePresence } from 'motion/react';
import { TestResult } from '../types';

interface ConceptFormationTestProps {
  onComplete: (result: TestResult) => void;
}

interface CardStimulus {
  id: number;
  color: 'red' | 'blue' | 'green' | 'yellow';
  shape: 'circle' | 'triangle' | 'square' | 'star';
  number: 1 | 2 | 3 | 4;
}

interface Trial {
  id: number;
  cards: CardStimulus[];
  correctRule: 'color' | 'shape' | 'number';
  correctCard: number;
}

const COLORS = ['red', 'blue', 'green', 'yellow'] as const;
const SHAPES = ['circle', 'triangle', 'square', 'star'] as const;
const NUMBERS = [1, 2, 3, 4] as const;

const COLOR_CLASSES = {
  red: 'bg-red-500',
  blue: 'bg-blue-500',
  green: 'bg-green-500',
  yellow: 'bg-yellow-500'
};

export function ConceptFormationTest({ onComplete }: ConceptFormationTestProps) {
  const [stage, setStage] = useState<'instructions' | 'test' | 'results'>('instructions');
  const [currentTrial, setCurrentTrial] = useState(0);
  const [currentRule, setCurrentRule] = useState<'color' | 'shape' | 'number'>('color');
  const [trials, setTrials] = useState<Trial[]>([]);
  const [responses, setResponses] = useState<number[]>([]);
  const [reactionTimes, setReactionTimes] = useState<number[]>([]);
  const [timeLeft, setTimeLeft] = useState(720); // 12分钟
  const [startTime, setStartTime] = useState<number>(0);
  const [trialStartTime, setTrialStartTime] = useState<number>(0);
  const [score, setScore] = useState(0);
  const [ruleChanges, setRuleChanges] = useState<number[]>([]);
  const [consecutiveCorrect, setConsecutiveCorrect] = useState(0);
  const [showFeedback, setShowFeedback] = useState(false);
  const [feedbackCorrect, setFeedbackCorrect] = useState(false);
  const [completedCategories, setCompletedCategories] = useState<string[]>([]);

  const TARGET_CARD: CardStimulus = {
    id: -1,
    color: 'red',
    shape: 'triangle',
    number: 2
  };

  const TRIALS_TO_COMPLETE = 128;
  const CONSECUTIVE_FOR_RULE_CHANGE = 10;

  const generateCard = (): CardStimulus => ({
    id: Math.random(),
    color: COLORS[Math.floor(Math.random() * COLORS.length)],
    shape: SHAPES[Math.floor(Math.random() * SHAPES.length)],
    number: NUMBERS[Math.floor(Math.random() * NUMBERS.length)]
  });

  const generateTrial = (rule: 'color' | 'shape' | 'number'): Trial => {
    const cards: CardStimulus[] = [];
    let correctCardIndex = Math.floor(Math.random() * 4);
    
    // 生成4张卡片
    for (let i = 0; i < 4; i++) {
      let card = generateCard();
      
      // 确保有一张卡片符合当前规则
      if (i === correctCardIndex) {
        switch (rule) {
          case 'color':
            card.color = TARGET_CARD.color;
            break;
          case 'shape':
            card.shape = TARGET_CARD.shape;
            break;
          case 'number':
            card.number = TARGET_CARD.number;
            break;
        }
      } else {
        // 确保其他卡片不完全匹配规则
        switch (rule) {
          case 'color':
            while (card.color === TARGET_CARD.color) {
              card = generateCard();
            }
            break;
          case 'shape':
            while (card.shape === TARGET_CARD.shape) {
              card = generateCard();
            }
            break;
          case 'number':
            while (card.number === TARGET_CARD.number) {
              card = generateCard();
            }
            break;
        }
      }
      
      cards.push(card);
    }

    return {
      id: currentTrial,
      cards,
      correctRule: rule,
      correctCard: correctCardIndex
    };
  };

  useEffect(() => {
    if (stage === 'test') {
      const newTrial = generateTrial(currentRule);
      setTrials([newTrial]);
      setTrialStartTime(Date.now());
    }
  }, [stage, currentTrial, currentRule]);

  useEffect(() => {
    let interval: NodeJS.Timeout;
    if (stage === 'test' && timeLeft > 0) {
      interval = setInterval(() => {
        setTimeLeft(prev => {
          if (prev <= 1) {
            setStage('results');
            return 0;
          }
          return prev - 1;
        });
      }, 1000);
    }
    return () => clearInterval(interval);
  }, [stage, timeLeft]);

  const handleStartTest = () => {
    setStage('test');
    setStartTime(Date.now());
  };

  const handleCardSelect = (cardIndex: number) => {
    const trial = trials[0];
    const reactionTime = Date.now() - trialStartTime;
    const correct = cardIndex === trial.correctCard;
    
    setResponses(prev => [...prev, cardIndex]);
    setReactionTimes(prev => [...prev, reactionTime]);
    
    if (correct) {
      setScore(prev => prev + 1);
      setConsecutiveCorrect(prev => prev + 1);
      
      // 检查是否需要改变规则
      if (consecutiveCorrect + 1 >= CONSECUTIVE_FOR_RULE_CHANGE) {
        changeRule();
      }
    } else {
      setConsecutiveCorrect(0);
    }
    
    // 显示反馈
    setFeedbackCorrect(correct);
    setShowFeedback(true);
    
    setTimeout(() => {
      setShowFeedback(false);
      
      if (currentTrial < TRIALS_TO_COMPLETE - 1) {
        setCurrentTrial(prev => prev + 1);
        setTrialStartTime(Date.now());
      } else {
        setStage('results');
      }
    }, 1000);
  };

  const changeRule = () => {
    const currentRuleIndex = ['color', 'shape', 'number'].indexOf(currentRule);
    const availableRules = ['color', 'shape', 'number'].filter(rule => 
      !completedCategories.includes(rule)
    );
    
    if (availableRules.length > 1) {
      // 随机选择一个新规则
      const newRule = availableRules[Math.floor(Math.random() * availableRules.length)];
      if (newRule !== currentRule) {
        setCurrentRule(newRule);
        setRuleChanges(prev => [...prev, currentTrial]);
        setCompletedCategories(prev => [...prev, currentRule]);
        setConsecutiveCorrect(0);
      }
    }
  };

  const handleComplete = () => {
    const totalTrials = responses.length;
    const totalCorrect = responses.filter((response, index) => {
      const trialData = generateTrial(getRuleAtTrial(index));
      return response === trialData.correctCard;
    }).length;
    
    const overallAccuracy = Math.round((totalCorrect / totalTrials) * 100);
    const averageReactionTime = Math.round(
      reactionTimes.reduce((sum, rt) => sum + rt, 0) / reactionTimes.length
    );
    
    // 计算概念灵活性指标
    const ruleChangeSuccess = ruleChanges.length;
    const categoriesCompleted = completedCategories.length;
    const perseverativeErrors = calculatePerseverativeErrors();
    
    // 概念形成得分
    const flexibilityScore = Math.min(30, ruleChangeSuccess * 10);
    const accuracyScore = Math.min(50, overallAccuracy * 0.5);
    const speedScore = Math.max(0, 20 - (averageReactionTime / 100));
    const finalScore = Math.round(flexibilityScore + accuracyScore + speedScore);

    const timeUsed = Math.round((Date.now() - startTime) / 1000);

    const result: TestResult = {
      id: Date.now().toString(),
      testType: 'concept-formation',
      score: finalScore,
      completedAt: new Date(),
      duration: timeUsed,
      details: {
        totalTrials,
        totalCorrect,
        overallAccuracy,
        averageReactionTime,
        ruleChanges: ruleChangeSuccess,
        categoriesCompleted,
        perseverativeErrors,
        conceptualFlexibility: Math.round((ruleChangeSuccess / 3) * 100),
        adaptabilityIndex: Math.round(100 - (perseverativeErrors / totalTrials) * 100),
        totalScore: score
      }
    };

    onComplete(result);
  };

  const getRuleAtTrial = (trialIndex: number): 'color' | 'shape' | 'number' => {
    let currentRuleForTrial: 'color' | 'shape' | 'number' = 'color';
    for (const changePoint of ruleChanges) {
      if (trialIndex >= changePoint) {
        const rules = ['color', 'shape', 'number'];
        const currentIndex = rules.indexOf(currentRuleForTrial);
        currentRuleForTrial = rules[(currentIndex + 1) % rules.length] as 'color' | 'shape' | 'number';
      }
    }
    return currentRuleForTrial;
  };

  const calculatePerseverativeErrors = (): number => {
    let errors = 0;
    let previousRule: 'color' | 'shape' | 'number' | null = null;
    
    ruleChanges.forEach(changePoint => {
      // 在规则改变后的几个试次中计算持续性错误
      for (let i = 0; i < 5 && changePoint + i < responses.length; i++) {
        const trialIndex = changePoint + i;
        const response = responses[trialIndex];
        const currentRuleForTrial = getRuleAtTrial(trialIndex);
        
        if (previousRule && response !== generateTrial(currentRuleForTrial).correctCard) {
          // 检查是否仍在使用旧规则
          if (response === generateTrial(previousRule).correctCard) {
            errors++;
          }
        }
      }
      previousRule = getRuleAtTrial(changePoint);
    });
    
    return errors;
  };

  const renderCard = (card: CardStimulus, index: number) => {
    const renderShape = () => {
      const shapeClass = `w-6 h-6 ${COLOR_CLASSES[card.color]}`;
      switch (card.shape) {
        case 'circle':
          return <div className={`${shapeClass} rounded-full`} />;
        case 'triangle':
          return <div className={`${shapeClass} rotate-0`} style={{ clipPath: 'polygon(50% 0%, 0% 100%, 100% 100%)' }} />;
        case 'square':
          return <div className={`${shapeClass} rounded-sm`} />;
        case 'star':
          return <div className={`${shapeClass} rounded-sm transform rotate-45`} />;
        default:
          return <div className={`${shapeClass} rounded-full`} />;
      }
    };

    return (
      <motion.div
        key={`${card.id}-${index}`}
        whileHover={{ scale: 1.05 }}
        whileTap={{ scale: 0.95 }}
      >
        <Button
          onClick={() => handleCardSelect(index)}
          variant="outline"
          className="w-32 h-32 p-4 border-2 hover:border-violet-400 hover:bg-violet-50 transition-all duration-200"
        >
          <div className="flex flex-wrap gap-1 items-center justify-center">
            {Array.from({ length: card.number }, (_, i) => (
              <div key={i}>{renderShape()}</div>
            ))}
          </div>
        </Button>
      </motion.div>
    );
  };

  const renderTargetCard = () => {
    const renderShape = () => {
      const shapeClass = `w-4 h-4 ${COLOR_CLASSES[TARGET_CARD.color]}`;
      switch (TARGET_CARD.shape) {
        case 'triangle':
          return <div className={`${shapeClass}`} style={{ clipPath: 'polygon(50% 0%, 0% 100%, 100% 100%)' }} />;
        default:
          return <div className={`${shapeClass} rounded-full`} />;
      }
    };

    return (
      <div className="w-20 h-20 border-2 border-violet-300 rounded-lg flex items-center justify-center bg-violet-50">
        <div className="flex flex-wrap gap-1 items-center justify-center">
          {Array.from({ length: TARGET_CARD.number }, (_, i) => (
            <div key={i}>{renderShape()}</div>
          ))}
        </div>
      </div>
    );
  };

  if (stage === 'instructions') {
    return (
      <motion.div
        initial={{ opacity: 0, y: 20 }}
        animate={{ opacity: 1, y: 0 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-violet-200 shadow-lg">
          <CardHeader className="text-center pb-8">
            <div className="w-16 h-16 bg-gradient-to-br from-violet-700 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg">
              <GitBranch className="w-8 h-8 text-white" />
            </div>
            <CardTitle className="text-2xl text-slate-800">概念形成测试</CardTitle>
            <p className="text-slate-600 mt-2">测试您的抽象概念学习和规则发现能力</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="bg-gradient-to-r from-violet-50 to-purple-50 rounded-xl p-6 border border-violet-100">
              <h3 className="font-semibold text-violet-900 mb-4 flex items-center gap-2">
                <Star className="w-5 h-5" />
                测试说明
              </h3>
              <div className="space-y-3 text-slate-700">
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-violet-700 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">1</span>
                  <p>您需要找出隐藏的分类规则</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-violet-700 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">2</span>
                  <p>根据目标卡片，从4张卡片中选择匹配的一张</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-violet-700 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">3</span>
                  <p>分类规则可能是颜色、形状或数量</p>
                </div>
                <div className="flex gap-3">
                  <span className="w-6 h-6 bg-violet-700 text-white rounded-full flex items-center justify-center text-sm font-semibold flex-shrink-0 mt-0.5">4</span>
                  <p>规则会在您掌握后悄悄改变，需要快速适应</p>
                </div>
              </div>
            </div>

            {/* 示例 */}
            <div className="bg-slate-50 rounded-xl p-4 border border-slate-200">
              <h4 className="font-semibold text-slate-700 mb-3 text-center">示例</h4>
              <div className="flex items-center justify-center gap-6">
                <div className="text-center">
                  <div className="text-sm text-slate-600 mb-2">目标卡片</div>
                  {renderTargetCard()}
                </div>
                <div className="text-slate-400">→</div>
                <div className="text-center">
                  <div className="text-sm text-slate-600 mb-2">如果规则是"颜色"</div>
                  <div className="text-xs text-green-600">选择红色卡片</div>
                </div>
              </div>
            </div>

            <div className="grid md:grid-cols-3 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-violet-50 to-violet-100 rounded-xl border border-violet-200">
                <div className="text-2xl font-bold text-violet-700 mb-1">128</div>
                <div className="text-sm text-violet-700">试次</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-purple-700 mb-1">3</div>
                <div className="text-sm text-purple-700">规则类型</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-violet-50 to-purple-50 rounded-xl border border-violet-200">
                <div className="text-2xl font-bold text-slate-600 mb-1">12</div>
                <div className="text-sm text-slate-700">分钟限时</div>
              </div>
            </div>

            <Button 
              onClick={handleStartTest}
              className="w-full bg-gradient-to-r from-violet-700 to-purple-600 hover:from-violet-800 hover:to-purple-700 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              开始测试
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  if (stage === 'test') {
    const progress = (currentTrial / TRIALS_TO_COMPLETE) * 100;
    const trial = trials[0];

    if (!trial) return null;

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-4xl mx-auto space-y-6"
      >
        {/* 顶部状态栏 */}
        <div className="flex flex-col sm:flex-row gap-4 items-center justify-between">
          <div className="flex items-center gap-4">
            <Badge variant="outline" className="bg-violet-100 text-violet-700 border-violet-300">
              试次 {currentTrial + 1} / {TRIALS_TO_COMPLETE}
            </Badge>
            <Badge variant="outline" className="bg-purple-100 text-purple-700 border-purple-300">
              连对 {consecutiveCorrect}
            </Badge>
            <Badge variant="outline" className="bg-blue-100 text-blue-700 border-blue-300">
              规则变化 {ruleChanges.length}
            </Badge>
            <div className="flex items-center gap-2 text-slate-600">
              <Trophy className="w-4 h-4" />
              <span className="font-semibold">{score}</span>
            </div>
          </div>
          
          <div className="flex items-center gap-2">
            <Clock className="w-4 h-4 text-slate-500" />
            <span className={`font-mono text-lg font-bold ${timeLeft <= 120 ? 'text-red-500' : 'text-slate-700'}`}>
              {Math.floor(timeLeft / 60)}:{(timeLeft % 60).toString().padStart(2, '0')}
            </span>
          </div>
        </div>

        <Progress value={progress} className="h-2" />

        {/* 指导信息 */}
        <Card className="bg-gradient-to-r from-violet-50 to-purple-50 border-violet-200">
          <CardContent className="py-4">
            <div className="text-center">
              <h3 className="text-lg font-semibold text-violet-800">
                找出分类规则，选择与目标卡片匹配的卡片
              </h3>
              {consecutiveCorrect >= 5 && (
                <p className="text-sm text-orange-600 mt-1">
                  <RotateCcw className="w-4 h-4 inline mr-1" />
                  注意：规则可能已经改变！
                </p>
              )}
            </div>
          </CardContent>
        </Card>

        {/* 测试区域 */}
        <Card className="bg-white/90 backdrop-blur-sm border-violet-200 shadow-lg">
          <CardContent className="py-8">
            <div className="space-y-8">
              {/* 目标卡片 */}
              <div className="text-center">
                <h4 className="text-lg font-semibold text-slate-700 mb-4">目标卡片</h4>
                <div className="flex justify-center">
                  {renderTargetCard()}
                </div>
              </div>

              {/* 选择卡片 */}
              <div className="text-center">
                <h4 className="text-lg font-semibold text-slate-700 mb-4">选择匹配的卡片</h4>
                <div className="grid grid-cols-2 sm:grid-cols-4 gap-4 justify-items-center">
                  {trial.cards.map((card, index) => renderCard(card, index))}
                </div>
              </div>
            </div>
          </CardContent>
        </Card>

        {/* 反馈弹窗 */}
        <AnimatePresence>
          {showFeedback && (
            <motion.div
              initial={{ opacity: 0, y: -20 }}
              animate={{ opacity: 1, y: 0 }}
              exit={{ opacity: 0, y: -20 }}
              className="fixed top-20 left-1/2 transform -translate-x-1/2 z-50"
            >
              <Card className={`border-0 shadow-lg ${
                feedbackCorrect 
                  ? 'bg-green-500 text-white' 
                  : 'bg-red-500 text-white'
              }`}>
                <CardContent className="py-3 px-6">
                  <div className="flex items-center gap-3">
                    {feedbackCorrect ? (
                      <CheckCircle className="w-5 h-5" />
                    ) : (
                      <XCircle className="w-5 h-5" />
                    )}
                    <span className="font-semibold">
                      {feedbackCorrect ? '正确！' : '错误！'}
                    </span>
                  </div>
                </CardContent>
              </Card>
            </motion.div>
          )}
        </AnimatePresence>
      </motion.div>
    );
  }

  if (stage === 'results') {
    const totalTrials = responses.length;
    const totalCorrect = score;
    const overallAccuracy = Math.round((totalCorrect / totalTrials) * 100);
    const averageReactionTime = Math.round(
      reactionTimes.reduce((sum, rt) => sum + rt, 0) / reactionTimes.length
    );
    
    const ruleChangeSuccess = ruleChanges.length;
    const perseverativeErrors = calculatePerseverativeErrors();
    
    const flexibilityScore = Math.min(30, ruleChangeSuccess * 10);
    const accuracyScore = Math.min(50, overallAccuracy * 0.5);
    const speedScore = Math.max(0, 20 - (averageReactionTime / 100));
    const finalScore = Math.round(flexibilityScore + accuracyScore + speedScore);

    return (
      <motion.div
        initial={{ opacity: 0, scale: 0.95 }}
        animate={{ opacity: 1, scale: 1 }}
        className="max-w-2xl mx-auto"
      >
        <Card className="bg-white/90 backdrop-blur-sm border-violet-200 shadow-xl">
          <CardHeader className="text-center pb-6">
            <motion.div
              initial={{ scale: 0 }}
              animate={{ scale: 1 }}
              transition={{ delay: 0.2, type: "spring", stiffness: 200 }}
              className="w-20 h-20 bg-gradient-to-br from-violet-700 to-purple-600 rounded-2xl flex items-center justify-center mx-auto mb-4 shadow-lg"
            >
              <Trophy className="w-10 h-10 text-white" />
            </motion.div>
            
            <CardTitle className="text-3xl text-slate-800 mb-2">测试完成！</CardTitle>
            <div className="text-6xl font-bold bg-gradient-to-r from-violet-700 to-purple-600 bg-clip-text text-transparent">
              {finalScore}
            </div>
            <p className="text-slate-600">概念形成能力得分</p>
          </CardHeader>
          
          <CardContent className="space-y-6">
            <div className="grid grid-cols-2 gap-4">
              <div className="text-center p-4 bg-gradient-to-br from-violet-50 to-violet-100 rounded-xl border border-violet-200">
                <div className="text-2xl font-bold text-violet-700 mb-1">{ruleChangeSuccess}</div>
                <div className="text-sm text-violet-700">成功规则转换</div>
              </div>
              <div className="text-center p-4 bg-gradient-to-br from-purple-50 to-purple-100 rounded-xl border border-purple-200">
                <div className="text-2xl font-bold text-purple-700 mb-1">{overallAccuracy}%</div>
                <div className="text-sm text-purple-700">总准确率</div>
              </div>
            </div>

            <div className="space-y-3">
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">概念灵活性</span>
                <span className="font-semibold text-slate-800">{Math.round((ruleChangeSuccess / 3) * 100)}%</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">持续性错误</span>
                <span className="font-semibold text-slate-800">{perseverativeErrors}</span>
              </div>
              <div className="flex justify-between items-center p-3 bg-slate-50 rounded-lg">
                <span className="text-slate-600">完成试次</span>
                <span className="font-semibold text-slate-800">{totalTrials}</span>
              </div>
            </div>

            <Button 
              onClick={handleComplete}
              className="w-full bg-gradient-to-r from-violet-700 to-purple-600 hover:from-violet-800 hover:to-purple-700 text-white py-3 text-lg font-semibold shadow-lg hover:shadow-xl transition-all duration-200"
              size="lg"
            >
              查看详细结果
            </Button>
          </CardContent>
        </Card>
      </motion.div>
    );
  }

  return null;
}